'''
Created on 07/04/2009

@author: Edward
'''
from im.ds import dsconstants, dsofactory
from im.ds.dso import DSO
from im.ds.dsstub import DSStub
from im.ds.dst import DST
from im.event import eventconstants
from im.event.event import Event
from im.event.eventhandler import BaseEventHandler
from im.event.eventmanager import EventManager
from im.handler import messagetypeconstants
from xml.etree import ElementTree
import datetime
import httplib
import os

class PublicApplicationStatusWebServiceResponseHandler(BaseEventHandler):
    
    def get_sub_element_text(self, element, tag_name):
        sub_element = element.find(tag_name)
        if sub_element is not None:
            return sub_element.text
        else:
            return None
        
    def do(self, data):
        dso = data
                
        web_service_response_dst = dso.get_dst(subject=dsconstants.SUBJECT_ROOT, 
                predicate=dsconstants.PREDICATE_WEB_SERVICE_RESPONSE)
        web_service_response = web_service_response_dst.get_literal()

        message_request_node_dst = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_MESSAGE_REQUEST_NODE)        
        message_request_node = message_request_node_dst.get_literal()
        
        spear_reference_number_dst = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
                                 predicate=dsconstants.PREDICATE_SPEAR_REFERENCE_NUMBER)
        
        application = ElementTree.XML(web_service_response)

        client_name = None               
        property_address = None
        application_type = None
        permit_category_type = None
        council_name = None
        application_state = None
        documents = []
        cc_version = None
        
        response_code = application.find('.//{http://response.webservice.spear.lx.dse.vic.gov.au}code').text
        response_message = application.find('.//{http://response.webservice.spear.lx.dse.vic.gov.au}message').text
        if response_code == "000":
            client_name = self.get_sub_element_text(application, './/{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}clientName')
            property_address = self.get_sub_element_text(application, './/{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}address')               
            application_type = self.get_sub_element_text(application, './/{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}applicationType')
            permit_category_type = self.get_sub_element_text(application, './/{http://permitCategory.was6.webservice.spear.lx.dse.vic.gov.au}permitCategoryType')
            council_name = self.get_sub_element_text(application, './/{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}councilName')
            application_state = self.get_sub_element_text(application, './/{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}applicationState')
            for document in application.findall('.//{http://application.response.webservice.spear.lx.dse.vic.gov.au}documentType'):
                if document.text is not None:
                    documents.append(str(document.text))
            cc_version = self.get_sub_element_text(application, './/{http://application.response.was6.webservice.spear.lx.dse.vic.gov.au}ccVersion')   

        request_id_dst = dso.get_dst(subject=dsconstants.SUBJECT_ROOT, 
                predicate=dsconstants.PREDICATE_REQUEST_ID)
        
        message_content_dst = DST(subject=dsconstants.SUBJECT_ROOT,
            predicate=dsconstants.PREDICATE_MESSAGE_CONTENT,
            object=dsconstants.SUBJECT_MESSAGE_CONTENT)

        response_code_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_RESPONSE_CODE,
            literal=response_code)

        response_message_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_RESPONSE_MESSAGE,
            literal=response_message)

        client_name_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_CLIENT_NAME,
            literal=client_name)

        property_address_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_PROPERTY_ADDRESS,
            literal=property_address)

        application_type_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_APPLICATION_TYPE,
            literal=application_type)

        permit_category_type_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_PERMIT_CATEGORY_TYPE,
            literal=permit_category_type)
                                                
        council_name_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_COUNCIL_NAME,
            literal=council_name)

        application_state_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_APPLICATION_STATE,
            literal=application_state)
        
        documents_dsts = []
        for document in documents:
            document_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
                predicate=dsconstants.PREDICATE_DOCUMENT,
                literal=document)
            documents_dsts.append(document_dst)
        
        cc_version_dst = DST(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
            predicate=dsconstants.PREDICATE_CC_VERSION,
            literal=cc_version)                        
        
        message_destination_node_dst = DST(subject=dsconstants.SUBJECT_ROOT,
            predicate=dsconstants.PREDICATE_MESSAGE_DESTINATION_NODE,
            literal=message_request_node)

        message_type_dst = DST(subject=dsconstants.SUBJECT_ROOT, 
            predicate=dsconstants.PREDICATE_MESSAGE_TYPE, 
            literal=messagetypeconstants.PUBLIC_APPLICATION_STATUS_TEST_RESPONSE_MESSAGE_TYPE)
                        
        new_dsts = [request_id_dst,
                message_content_dst,
                response_code_dst,
                response_message_dst,
                client_name_dst,
                property_address_dst,
                application_type_dst,
                permit_category_type_dst,
                council_name_dst,
                application_state_dst,
                cc_version_dst,
                message_destination_node_dst,
                message_type_dst,
                spear_reference_number_dst]
        new_dsts.extend(documents_dsts)
        
        new_dso = DSO(dsts=new_dsts)
        event = Event(eventconstants.SEND_TO_HUB_EVENT_TYPE, new_dso)
        EventManager().add_event(event)

class PublicApplicationStatusTestHTTPResponseHandler(BaseEventHandler):
    def do(self, data):
        dso = data
        request_id = dso.get_dst(subject=dsconstants.SUBJECT_ROOT, 
                                 predicate=dsconstants.PREDICATE_REQUEST_ID).get_literal()
        ds = DSStub()
        
        result = ds.get_outstanding_requests(int(request_id))
        if result:
            (http_request, lock) = result
        else:
            print 'Cannot find message entry with request_id ' + request_id
            return
      
        response_code = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_RESPONSE_CODE).get_literal()
        response_message = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_RESPONSE_MESSAGE).get_literal()
        client_name = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_CLIENT_NAME).get_literal()
        property_address = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_PROPERTY_ADDRESS).get_literal()
        application_type = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_APPLICATION_TYPE).get_literal()                                 
        permit_category_type = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_PERMIT_CATEGORY_TYPE).get_literal()
        council_name = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_COUNCIL_NAME).get_literal()
        application_state = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_APPLICATION_STATE).get_literal()
        document_dsts = dso.get_dsts(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_DOCUMENT)
        cc_version = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT, 
                                 predicate=dsconstants.PREDICATE_CC_VERSION).get_literal()                                                                                                                                    
        spear_reference_number = dso.get_dst(subject=dsconstants.SUBJECT_MESSAGE_CONTENT,
                                         predicate=dsconstants.PREDICATE_SPEAR_REFERENCE_NUMBER).get_literal()                                 
        
        relative_path = None
        if response_code == "000":
            relative_path = "../../../pages/im/public-application-status-test-result.html"
        else:
            relative_path = "../../../pages/im/imerror.html"
        
        # get the html template
        template_path = os.path.join(os.path.dirname(__file__), relative_path)
        file = open(template_path)
        html_template_string = file.read()
        html_string = None
        if application_state:
            if document_dsts:
                document_list_html = ""
                for document_dst in document_dsts:
                    document_list_html += str(document_dst.get_literal()) + "<br/>"
            html_string = html_template_string.replace('${spear_reference_number}', spear_reference_number) \
                                                .replace('${response_code}', response_code) \
                                                .replace('${response_message}', str(response_message)) \
                                                .replace('${client_name}', str(client_name)) \
                                                .replace('${property_address}', str(property_address)) \
                                                .replace('${application_type}', str(application_type)) \
                                                .replace('${permit_category_type}', str(permit_category_type)) \
                                                .replace('${council_name}', str(council_name)) \
                                                .replace('${application_state}', str(application_state)) \
                                                .replace('${documents}', document_list_html) \
                                                .replace('${cc_version}', str(cc_version))
                                                
        else:
            html_string = html_template_string.replace('${fault_message}', "unknown-spear-reference")
        new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                               'text/html', 
                                                               html_string, 
                                                               http_request, 
                                                               lock)
        event = Event(eventconstants.HTTP_RESPONSE_EVENT_TYPE, new_dso)
        EventManager().add_event(event)
        print 'End Request: ' + str(datetime.datetime.now())    